package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseArrayDialogFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseSearchListFragment;
import com.isunland.managesystem.base.BaseSelectObject;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.FileListParams;
import com.isunland.managesystem.entity.LocaleWorkQueryCount;
import com.isunland.managesystem.entity.Plotmappinginformation;
import com.isunland.managesystem.entity.WorkAreaSearchParams;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2016/12/16 15:45
 */

public class LocaleWorkQueryCountUpdateFragment extends LocaleWorkQueryCountBaseFragment
    implements View.OnClickListener {

  public static LocaleWorkQueryCountUpdateFragment newInstance(LocaleWorkQueryCount item) {
    LocaleWorkQueryCountUpdateFragment fragment = new LocaleWorkQueryCountUpdateFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_ITEM, item);
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    init();
  }

  private void init() {
    String title = mItem == null ? "作业信息填报" : "作业信息修改";
    setTitleCustom(title);
    mFm = getActivity().getSupportFragmentManager();
    //initView
    slRegStaffNameWork.setVisibility(View.GONE);
    slRegDateWork.setVisibility(View.GONE);
    slDataStatusName.setVisibility(View.GONE);
    slCheckStaffName.setVisibility(View.GONE);
    slWorktypeshowvalue.setOnClickContentListener(this);
    slJoinStaffName.setOnClickContentListener(this);
    slWorkernames.setOnClickContentListener(this);
    slDeviceName.setOnClickContentListener(this);
    slWorkstartdate.setOnClickContentListener(this);
    slWorkenddate.setOnClickContentListener(this);
    slIspayName.setOnClickContentListener(this);
    slWeatherName.setOnClickContentListener(this);
    slAreaname.setOnClickContentListener(this);
    slDocBlob.setOnClickContentListener(this);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_order_save_submit, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    //if (item == null) return super.onOptionsItemSelected(item);
    switch (item.getItemId()) {

      case R.id.menu_item_save:
        volleyPostSave(TYPE_SAVE);
        return true;
      case R.id.menu_item_submit:
        volleyPostSave(TYPE_SUBMIT);
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave(final int type) {
    //if (mWorkEndDate == null || mMedicine == null || mType == null || mObject == null || mMan == null || mEquipMent == null) {
    //    ToastUtil.show("请填写完整!");
    //    return ;
    //}
    if (TextUtils.isEmpty(mId)) return;
    String worktypeshowvalue = slWorktypeshowvalue.getTextContent();
    String workernames = slWorkernames.getTextContent();
    String joinStaffName = slJoinStaffName.getTextContent();
    String workstartdate = slWorkstartdate.getTextContent();
    String workenddate = slWorkenddate.getTextContent();
    String deviceName = slDeviceName.getTextContent();
    String deviceNo = slDeviceNo.getTextContent();

    if (TextUtils.isEmpty(mJoinStaffId) || TextUtils.isEmpty(joinStaffName)) {
      ToastUtil.show(R.string.notComplete);
      return;
    }

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_LOCALE_WORK);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("worktype", mWorktype);
    params.put("worktypeshowvalue", worktypeshowvalue);
    params.put("workerids", mWorkerIds);
    params.put("workernames", workernames);
    params.put("joinStaffId", mJoinStaffId);
    params.put("joinStaffName", joinStaffName);
    params.put("workstartdate", workstartdate);
    params.put("workenddate", workenddate);
    params.put("devicecode", deviceName);//devicecode里的是名称.注意详情修改.
    params.put("deviceNo", deviceNo);
    params.put("weatherId", mWeatherId == null ? "" : mWeatherId);
    params.put("weatherName", slWeatherName.getTextContent());
    params.put("weatherInfo", slWeatherInfo.getTextContent());
    params.put("price", slPrice.getTextContent());
    params.put("othercost", slOtherCost.getTextContent());
    params.put("totalcost", slTotalcost.getTextContent());
    params.put("ispay", mIsPay);
    params.put("payedcost", slPayedcost.getTextContent());
    params.put("unpay", slUnpay.getTextContent());
    params.put("regStaffId", CurrentUser.newInstance(mActivity).getJobNumber());
    params.put("regStaffName", CurrentUser.newInstance(mActivity).getName());
    //noinspection deprecation
    params.put("regDate", MyDateUtil.parseDateToString(new Date()));
    params.put("remark", slRemarkWork.getTextContent());
    params.put("dataStatus", mDataStatus);
    params.put("areaid", mAreaId);
    params.put("areaname", slAreaname.getTextContent());
    params.put("region", slRegion.getTextContent());
    params.put("area", slAreaWork.getTextContent());
    params.put("cropInfoTypeCode", mCropInfoTypeCode);
    params.put("cropInfoTypeName", slCropInfoTypeName.getTextContent());
    params.put("cropInfoNo", slCropInfoNo.getTextContent());
    params.put("cropInfoNum", slCropInfoNum.getTextContent());
    params.put("technicalParam", slTechnicalParam.getTextContent());
    params.put("landDeepth", slLandDeepth.getTextContent());
    params.put("warrantyCost", slWarrantyCost.getTextContent());
    params.put("oilNum", slOilNum.getTextContent());
    params.put("oilNo", slOilNo.getTextContent());
    params.put("repairUse", slRepairUse.getTextContent());
    params.put("workLocation", slWorkLocation.getTextContent());
    params.put("oldWeight", slOldWeight.getTextContent());
    params.put("afterProcessWeight", slAfterProcessWeight.getTextContent());
    params.put("electricityNum", slElectricityNum.getTextContent());
    params.put("waterNum", slWaterNum.getTextContent());
    params.put("pickupLocation", slPickupLocation.getTextContent());
    params.put("deliveryLocation", slDeliveryLocation.getTextContent());
    params.put("soilInfo", slSoilInfo.getTextContent());
    params.put("docBlob", slDocBlob.getTextContent());
    params.put("docPath", mDocPath);
    params.put("cropInfoMunit", mCropInfoMunit);
    params.put("longItude", mLon);
    params.put("latItude", mLat);

    params.put("comeFrome", "1");//标记来自于移动端

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("保存失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        Base original = new Gson().fromJson(json, Base.class);
        if (original.getResult() == Base.SUCCESS) {
          ToastUtil.show("保存成功");
          mActivity.setResult(Activity.RESULT_OK);
          if (type == TYPE_SAVE) {
            mActivity.finish();
          }
          if (type == TYPE_SUBMIT) {
            volleyPostUpdateStatus(mId, TYPE_SUBMIT);
          }
        } else {
          ToastUtil.show("保存失败!");
        }
      }
    });
    mActivity.setResult(Activity.RESULT_OK);
    mActivity.finish();
  }

  protected void showDialog(Date date, int typeCode) {
    DialogFragment dialog = BaseYMDTimeDialogFragment.newInstance(date);
    dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, typeCode);
    dialog.show(mFm, "");
  }

  protected void showDialog(final ArrayList<BaseSelectObject> rows, int typeCode) {

    BaseArrayDialogFragment dialog = SimpleArrayDialogFragment.newInstance(rows);
    if (dialog == null) return;
    dialog.setTargetFragment(this, typeCode);
    dialog.show(mFm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == REQUEST_WORK_TYPE_SHOW_VALUE && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slWorktypeshowvalue.setTextContent(value.getName());
      mWorktype = value.getId();
      showDynamicView(value.getJobNo());
    }
    if (requestCode == REQUEST_JOIN_STAFF_NAME && data != null) {
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      if (dialog == null) return;
      slJoinStaffName.setTextContent(dialog.getName());
      mJoinStaffId = dialog.getJobNo();
    }
    if (requestCode == REQUEST_WORKER_NAMES && data != null) {
      String names = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      String jobNos = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      slWorkernames.setTextContent(names);
      mWorkerIds = jobNos;
    }
    if (requestCode == REQUEST_DEVICENO_WORK && data != null) {

      slDeviceName.setTextContent(data.getStringExtra(RDeviceListListFragment.EXTRA_NAMES));
      slDeviceNo.setTextContent(data.getStringExtra(RDeviceListListFragment.EXTRA_NOS));
    }
    if (requestCode == REQUEST_WORK_START_DATE && data != null) {
      Date date = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      slWorkstartdate.setTextContent(DateFormat.format(MyDateUtil.TYPE_ALL, date).toString());
      sameDay(slWorkstartdate, slWorkenddate, date);
    }
    if (requestCode == REQUEST_WORK_END_DATE && data != null) {
      Date date = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      slWorkenddate.setTextContent(DateFormat.format(MyDateUtil.TYPE_ALL, date).toString());
      sameDay(slWorkstartdate, slWorkenddate, date);
    }

    if (requestCode == REQUEST_WEATHER_TYPE && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slWeatherName.setTextContent(value.getName());
      mWeatherId = value.getId();
    }
    if (requestCode == REQUEST_ISPAY_NAME && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slIspayName.setTextContent(value.getName());
      mIsPay = value.getId();
    }
    if (requestCode == REQUEST_WORK_AREA && data != null) {
      //CustomerDialog value = (CustomerDialog) data
      //        .getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      Plotmappinginformation value =
          (Plotmappinginformation) data.getSerializableExtra(BaseSearchListFragment.EXTRA_ITEM);
      slAreaname.setTextContent(value.getWplotDepict());
      slRegion.setTextContent(value.getRegion());
      slAreaWork.setTextContent(value.getPlotArea());
      mAreaId = value.getId();
      mLat = value.getLatItude();
      mLon = value.getLongItude();
      //mIsPay = value.getId();
    }
    //noinspection StatementWithEmptyBody
    if (requestCode == REQUEST_CROP_INFO && data != null) {
      //rProductsListMain value=(rProductsListMain)data.getSerializableExtra(BaseSearchListFragment.EXTRA_ITEM);
      //slCropInfoTypeName.setTextContent(value.getProductName());
      //slCropInfoNo.setTextContent(value.getMtype());
      //mCropInfoTypeCode = value.getId();
      //mCropInfoMunit = value.getMunit();
      //slCropInfoNum.setTextTitle(getDynamicUnitTilte(value.getMunit()));
    }
    if (requestCode == REQUEST_SELECT_FILE && data != null) {
      String path = FileUtil.getPath(getActivity(), data.getData());
      if (!TextUtils.isEmpty(path)) {

        FileUploadDialgFragment dialog =
            FileUploadDialgFragment.newInstance(path, mId, "imsifwj.locale_work_query_count");
        dialog.setTargetFragment(this, REQUEST_UPLOAD);
        dialog.show(mActivity.getSupportFragmentManager(), "");
      }
    }
    if (requestCode == REQUEST_UPLOAD) {
      mDocPath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      slDocBlob.setTextContent(FileUtil.getFileNameByFilePath(mDocPath));
    }
  }

  private void sameDay(SingleLineView slWorkstartdate, SingleLineView slWorkenddate, Date date) {
    if (TextUtils.isEmpty(slWorkstartdate.getTextContent()) || TextUtils.isEmpty(
        slWorkenddate.getTextContent())) {
      return;
    }
    //noinspection deprecation
    Date startDate = MyDateUtil.parseStringToTime(slWorkstartdate.getTextContent());
    //noinspection deprecation
    Date endDate = MyDateUtil.parseStringToTime(slWorkenddate.getTextContent());

    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);

    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);

    Calendar laterCalendar = Calendar.getInstance();
    laterCalendar.setTime(date);

    int laterDay = laterCalendar.get(Calendar.DAY_OF_YEAR);

    startCalendar.set(Calendar.DAY_OF_YEAR, laterDay);
    endCalendar.set(Calendar.DAY_OF_YEAR, laterDay);

    startDate = startCalendar.getTime();
    endDate = endCalendar.getTime();
    //noinspection deprecation
    slWorkstartdate.setTextContent(MyDateUtil.parseTimeToString(startDate));
    //noinspection deprecation
    slWorkenddate.setTextContent(MyDateUtil.parseTimeToString(endDate));
  }

  @Override public void onClick(View v) {
    super.onClick(v);
    if (!(v.getTag() instanceof Integer)) return;
    int id = (int) v.getTag();
    switch (id) {
      case R.id.sl_worktypeshowvalue:
        selectWorkType();
        break;
      case R.id.sl_joinStaffName:
        selecJoinStaffName();
        break;
      case R.id.sl_workernames:
        selectWorkerNames();
        break;
      case R.id.sl_devicename:
        selectDevice();
        break;
      case R.id.sl_workstartdate:
        selectDate(slWorkstartdate.getTextContent(), REQUEST_WORK_START_DATE);
        break;
      case R.id.sl_workenddate:
        selectDate(slWorkenddate.getTextContent(), REQUEST_WORK_END_DATE);
        break;
      case R.id.sl_ispayName:
        selectIsPay();
        break;
      case R.id.sl_weatherName:
        selectWeatherType();
        break;
      case R.id.sl_areaname:
        selectArea();
        break;

      case R.id.sl_docBlob:
        selectDoc();
        break;
    }
  }

  /**
   * 选择附件上传
   */
  private void selectDoc() {
    //Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    //intent2.setType("*/*");
    //intent2.addCategory(Intent.CATEGORY_OPENABLE);
    //startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
    //    REQUEST_SELECT_FILE);

    //相关附件子表
    FileListParams params = new FileListParams();
    params.setMainId(mId);
    BaseVolleyActivity.newInstance(this, FileListActivity.class, params, 0);
  }

  private void selectArea() {
    if (TextUtils.isEmpty(mWorktype)) {
      ToastUtil.show(MyStringUtil.connect(R.string.pleaseSelect, R.string.worktypeshowvalue1));
      return;
    }
    WorkAreaSearchParams params = new WorkAreaSearchParams();
    params.setShowSelect(true);
    params.setWorkId(mId);
    params.setWorktype(mWorktype);
    params.setIfWork(true);
    params.setLatItude(mLat);
    params.setLongItude(mLon);
    BaseVolleyActivity.newInstance(this, WorkAreaSearchListActivity.class, params,
        REQUEST_WORK_AREA);
  }

  private void selectWorkerNames() {
    Intent i = new Intent(getActivity(), SearchPersonMultipleActicity.class);
    i.putExtra(SearchPersonMultipleFragment.EXTRA_FROM, SearchPersonMultipleFragment.VALUE_COMMON);
    i.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, mWorkerIds);
    startActivityForResult(i, REQUEST_WORKER_NAMES);
  }

  private void selecJoinStaffName() {
    Intent i = new Intent(getActivity(), SearchPersonActivity.class);
    i.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
    //i.putExtra(SearchPersonListFragment.EXTRA_JOB, mJoinStaffId);
    startActivityForResult(i, REQUEST_JOIN_STAFF_NAME);
  }

  protected void selectDate(String date, int typeCode) {
    //noinspection deprecation
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(MyDateUtil.parseStringToTime(date));
    dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, typeCode);
    dialog.show(mFm, "");
  }

  /**
   * 选择作业类别
   */
  private void selectWorkType() {
    DialogFragment dialog = new WorkTypeDialogFragment();
    dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, REQUEST_WORK_TYPE_SHOW_VALUE);
    dialog.show(mFm, "");
  }

  private void selectWeatherType() {
    DialogFragment dialog = new WeatherTypeDialogFragment();
    dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, REQUEST_WEATHER_TYPE);
    dialog.show(mFm, "");
  }

  private void selectDevice() {
    //DialogFragment dialog = new DeviceListDialogFragment();
    //dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, REQUEST_DEVICENO_WORK);
    //dialog.show(mFm, "");
    Intent i = new Intent(mActivity, RDeviceListListActivity.class);
    i.putExtra(RDeviceListListFragment.EXTRA_NOS, slDeviceNo.getTextContent());
    startActivityForResult(i, REQUEST_DEVICENO_WORK);
  }

  private void selectIsPay() {
    DialogFragment dialog = new IsPayDialogFragment();
    dialog.setTargetFragment(LocaleWorkQueryCountUpdateFragment.this, REQUEST_ISPAY_NAME);
    dialog.show(mFm, "");
  }
}
